package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public void start() {
        // TODO: [222024321072055/苏雨征] 实现 ServerSocket 的创建和监听
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());
            System.out.println("Web 根目录：" + config.getWebRoot());

            //无限循环监听客户端连接（服务器主循环）
            while (!serverSocket.isClosed()) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到新的连接：" + clientSocket.getInetAddress()+
                        ",端口："+clientSocket.getPort());

                threadPool.execute(new RequestProcessor(clientSocket));
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
            System.out.println("服务器已停止，线程池已关闭");
        }
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // TODO: [222024321072055/苏雨征] 完善请求处理流程，确保异常安全和资源关闭
            OutputStream outputStream=null;
            try {
                outputStream=socket.getOutputStream();

                Parameter request = HttpParser.parse(socket.getInputStream());
                System.out.println("处理请求："+request.getMethod()+" "+request.getUrl());

                Router router = new Router();
                router.route(request, socket.getOutputStream());

            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                e.printStackTrace();
                // TODO: [222024321072055/苏雨征] 可以在这里实现返回 500 错误页面的逻辑
                if (outputStream != null) {
                    try {
                        String errorMsg = "HTTP/1.1 500 Internal Server Error\r\n" +
                                "Content-Type: text/html; charset=UTF-8\r\n" +
                                "Content-Length: " + e.getMessage().length() + "\r\n" +
                                "\r\n" +
                                "<h1>500 Internal Server Error</h1>\r\n" +
                                "<p>" + e.getMessage() + "</p>";
                        outputStream.write(errorMsg.getBytes(StandardCharsets.UTF_8));
                        outputStream.flush();
                    } catch (IOException ex) {
                        System.err.println("错误响应发送失败: " + ex.getMessage());
                    }
                }
            } finally {
                try{
                    if (outputStream != null){
                        outputStream.close();
                    }
                }catch (IOException e) {
                    System.err.println("输出流关闭失败: " + e.getMessage());
                }
                try{
                    if (socket != null && !socket.isClosed()) {
                        socket.close();
                        System.out.println("连接已关闭："+socket.getInetAddress());
                    }
                } catch (IOException e) {
                    System.err.println("客户端连接关闭失败："+e.getMessage());
                }
            }
        }
    }
}

